<template>
  <div id="catalogue_Details">
    <!-- 返回按钮 -->
    <div>
      <RightContainer>
        <template v-slot:operate-btn>
          <el-button type="primary" @click="showAdd()" size="small" class="mr10">新增</el-button>
          <!-- <el-button type="danger" @click="del" size="small">删除</el-button> -->
          <el-input @keyup.enter.native="getList" placeholder="请输入业务名" clearable size="small" style="width: 300px"
            suffix-icon="el-icon-search" v-model="query.modelExampleName">
            <!-- <el-select style="width: 100px; color: #37adff" size="small" v-model="selectVal" slot="prepend">
              <el-option label="业务名" value="业务名"></el-option>
              <el-option label="分区大小" value="分区大小"></el-option>
              <el-option label="挂载点" value="挂载点"></el-option>
            </el-select> -->
          </el-input>
        </template>

        <!-- 列表 -->
        <template v-slot:data>
          <el-table v-loading="loading" :data="tableData" :header-cell-style="{ backhround: '#eee' }"
            height="calc(100vh - 230px)" style="cursor: pointer" @selection-change="handleSelectionChange"
            @row-click="handleRowClick" :cell-style="cellStyle">
            <el-table-column type="selection" width="50" align="left" />
            <!-- <el-table-column label="ID" align="left" sortable>
              <template slot-scope="scope">
                <a
                  href="javascript:void(0)"
                  style="color: #37adff"
                  @click="
                    toCatalogueDetail(
                      scope.row.model_example_id,
                      scope.row.model_id
                    )
                  "
                  >{{ scope.row.model_example_id }}</a
                >
              </template>
            </el-table-column> -->
            <el-table-column label="业务名" align="left" prop="model_example_name" sortable></el-table-column>
            <el-table-column v-for="item in tableFIelds" :key="item.modelFieldId" :label="item.comment" align="left"
              :prop="item.newFieldName" sortable></el-table-column>
            <el-table-column label="操作" align="left" prop="operate">
              <template slot-scope="scope">
                <el-button @click.native.stop="delExample(scope.row.model_example_id)" size="mini"
                  type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize"
            :select-data-len="multipleSelection.length" @pagination="getList()" />
        </template>
      </RightContainer>
    </div>

    <!-- 新增实例弹窗 -->
    <el-dialog title="新增业务实例 " :visible.sync="dialogVisible" class="member-info-modal">
      <el-form class="addForm" ref="addForm" label-position="right" :model="addForm" :rules="rules" label-width="100px"
        size="mini">
        <el-form-item label="业务名" prop="model_example_name">
          <el-input v-model="addForm.model_example_name" placeholder="请输入业务名" />
        </el-form-item>
        <el-form-item v-for="item in tableFIelds" :key="item.modelFieldId" :label="item.comment"
          :prop="item.newFieldName">
          <el-date-picker v-if="item.type == 'DATE'" v-model="addForm[item.newFieldName]" type="date"
            :placeholder="'请选择' + item.comment" value-format="yyyy-MM-dd">
          </el-date-picker>

          <el-date-picker v-else-if="item.type == 'DATETIME'" v-model="addForm[item.newFieldName]" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" :placeholder="'请选择' + item.comment">
          </el-date-picker>

          <el-input v-else v-model="addForm[item.newFieldName]" :placeholder="'请输入' + item.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addExample('addForm')">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RightContainer from "@/components/RightContainer";
import {
  getModelExampleList_Api, //根据模型id查询实例列表
  getModelIdCategoryList_Api, //根据模型id查询模型分组列表
  addModelExample_Api, //新增模型实例
  delModelExample_Api, //删除模型实例
} from "@/api/configuration/resource.js";
import {
  getCurrent_YMDHMS_Time, //获取当前年月日时分秒
} from "@/utils/common.js";
import {
  clearObj, //清空表单的值
} from "@/utils/index.js";
let queryIp = (rule, value, callback) => {
  const ipv4Regex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?::[0-9]{1,5})?$/;
  if (!ipv4Regex.test(value)) {
    callback(new Error("ip格式错误"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      id: "1691271600311410690",
      searchVal: "", //搜索
      //列表数据
      tableData: [],
      //列表字段数据
      tableFIelds: [],
      loading: false, //列表loading
      total: 0, //数据总条数
      //分页参数
      query: {
        pageNum: 1,
        pageSize: 10,
        modelId: "1691271600311410690",
        modelExampleName: "",
      },
      multipleSelection: [], //多选
      searchVal: "", //搜索
      selectVal: "业务名", //下拉框
      dialogVisible: false, //控制新增实例弹窗显示或隐藏
      //新建实例表单
      addForm: {
        model_example_name: "", //业务名
        special_example: 2, //特殊标识
      },
      // 表单校验
      rules: {
        model_example_name: [
          { required: true, message: `请输入业务名`, trigger: "blur" },
        ],
      },
    };
  },
  components: {
    RightContainer,
  },
  methods: {
    //获取列表字段信息
    getTableFields(id) {
      this.loading = true; //开启列表loading
      //查询字段
      getModelIdCategoryList_Api({ modelId: id }).then((res) => {
        if (res.data.length) {
          //列表字段生成
          res.data.forEach((item) => {
            this.tableFIelds = [...this.tableFIelds, ...item.cgModelFields];
          });
          // 表单验证生成
          this.tableFIelds.forEach((element) => {
            if (element.testingRegulationsJSON) {
              let arr = []
              JSON.parse(element.testingRegulationsJSON).forEach(item => {
                let obj = {}
                switch (item.type) {
                  case "max":
                    obj.max = Number(item.val)
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  case "min":
                    obj.min = Number(item.val)
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  case "number":
                    obj.type = item.type
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  case "string":
                    obj.type = item.type
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  case "ip":
                    obj.validator = queryIp
                    obj.trigger = item.trigger
                    break;
                  case "email":
                    obj.type = item.type
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  case "required":
                    obj.required = true
                    obj.trigger = item.trigger
                    obj.message = item.message
                    break;
                  default:
                    break;
                }
                arr.push(obj)
              })
              this.rules[element.newFieldName] = arr
            }
          });
        } else this.loading = false; //关闭列表loading
      });
    },
    //获取列表信息
    getList() {
      getModelExampleList_Api(this.query).then((res) => {
        this.total = res.total;
        this.tableData = res.rows;
        this.loading = false; //关闭列表loading
      });
    },
    showAdd() {
      this.dialogVisible = true;
      this.addForm = {
        model_example_name: "", //业务名
        special_example: 2,
      };
    },
    //新建实例
    addExample(formName) {
      //验证表单是否输入正确
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //正确
          this.addForm.modelId = this.id;

          // const newObj = {};
          // Object.keys(this.addForm).forEach((key) => {
          //   const newKey = key
          //     .replace(/([a-z])([A-Z])/g, "$1_$2")
          //     .toLowerCase(); // 将驼峰式转换为下划线间隔
          //   newObj[newKey] = this.addForm[key]; // 将原始值复制到更新后的键名
          // });

          addModelExample_Api(this.addForm)
            .then((res) => {
              this.getList(); //重新获取数据
              this.dialogVisible = false; //隐藏添加模版弹框
              this.$message.success("添加成功");
              this.addForm = clearObj(this.addForm); //清空表单
            })
            .catch((error) => { });
        } else {
          return false;
        }
      });
    },
    //删除实例
    delExample(id) {
      this.$confirm("此操作将永久删除该实例, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await delModelExample_Api(id);
          let { code, msg } = res;
          if (code == 200) {
            this.$message.success(msg);
            this.getList();
          } else {
            this.$message.error(msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //多选列表项
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row, column, event) {
      // 处理行点击事件
      this.toCatalogueDetail(row.model_example_id, row.model_id);
    },
    //跳转业务实例详情页面
    toCatalogueDetail(exampleId, modelId) {
      this.$router.push({
        path: `/configuration/resource/business_info?exampleId=${exampleId}&modelId=${modelId}`,
      });
    },
    //表格样式
    cellStyle({ column, columnIndex }) {
      // 状态列字体颜色
      if (columnIndex === 1) {
        return "color: #46a6ff;cursor:pointer;";
      }
    },
  },
  created() {
    //先获取列表字段信息
    this.getTableFields(this.id);
    //获取模型实例列表数据
    this.getList();
  },
};
</script>

<style lang="scss" scoped>
#catalogue_Details {
  border-radius: 5px;
}

.divider {
  margin: 0 10px;
  border: 1px solid #bbbbbb;
  height: 18px;
  display: inline-block;
  margin-bottom: -4px;
}

.addForm {
  max-height: 400px;
  overflow-y: scroll;
}
</style>
